package com.xcf.codec;

import com.alibaba.fastjson.JSON;
import com.xcf.model.RpcRequest;
import com.xcf.model.RpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;
import java.util.concurrent.Callable;

/**
 * 解码器
 */
public class RequestJsonDecoder extends ByteToMessageDecoder {

    private final Callable callable;

    public RequestJsonDecoder(Callable callable) {
        this.callable = callable;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        int length = in.readableBytes();
        try {
            if (length >= 4) {
                in.markReaderIndex();
                int msgLength = in.readInt();
                byte[] data = new byte[msgLength];
                ByteBuf tempBuff = in.readBytes(msgLength);
                tempBuff.getBytes(0, data, 0, msgLength);
                Object rpcResponse = JSON.parseObject(data, RpcResponse.class);
                out.add(rpcResponse);
            } else {
                synchronized (callable) {
                    callable.notify();
                }
                throw new RuntimeException("Msg length is error");
            }
        } catch (Throwable e) {
            synchronized (callable) {
                callable.notify();
            }
            throw e;
        }
    }

    public static void main(String[] args) {

    }
}
